// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        spriteframes: {
            type: cc.SpriteFrame,
            default: []
        },
        frame_time: 0.1,     //  动画切换间隔时间
        loop: true,         //  是否循环播放
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.isPlaying = false
        this.time = 0
        this.sprite = this.getComponent(cc.Sprite)
        if (!this.sprite) {
            this.sprite = this.addComponent(cc.Sprite)
        }
        this.play()
    },

    play () {
        if (this.spriteframes.length <= 0) {
            return
        }
        this.time = 0
        this.isPlaying = true
        this.end_fun = null
        // 初始化第一帧
        this.sprite.spriteFrame = this.spriteframes[0]
    },

    start () {
    },

    update (dt) {
        if (!this.isPlaying) {
            return
        }
        this.time += dt
        var index = Math.floor(this.time / this.frame_time)
        if (!this.loop) {
            // 一次播放
            if (index >= this.spriteframes.length) {
                this.isPlaying = false
                if (this.end_fun) {
                    this.end_fun()
                }
            } else {
                this.sprite.spriteFrame = this.spriteframes[index]
            }
        } else {
            // 循环播放
            if (index >= this.spriteframes.length) {
                index = 0
                this.time = 0
            }
            this.sprite.spriteFrame = this.spriteframes[index]
        }
    },
});
